package com.cx.core.redis.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.util.Collections;

@Service
public class StockService {


    @Autowired
    private RedisTemplate redisTemplate;

    public boolean initProductCount(String productId, int count) {
        //String key = 项目前缀 + id
        redisTemplate.opsForValue().set(productId, count);
        return true;
    }

    public int subProductCount(String productId, int decrement) {
        String luaScript =  "local productId = KEYS[1] local count = tonumber(ARGV[1])\n" +
                "local inventoryKey = 'inventory:' .. productId\n" +
                "local currentCount = tonumber(redis.call('get', inventoryKey) or '0')\n" +
                "if currentCount < count then\n" +
                "    return -1\n" +
                "else\n" +
                "    return redis.call('decrby', inventoryKey, count)\n" +
                "end";
        RedisScript redisScript = RedisScript.of(luaScript);
        Number result = (Number) redisTemplate.execute(redisScript, Collections.singletonList(productId), decrement);
        return result.intValue();
    }
}
